package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.MemberProductTime;
import cn.wolfcode.crm.domain.MemberProductTimeItem;
import cn.wolfcode.crm.mapper.MemberProductTimeItemMapper;
import cn.wolfcode.crm.mapper.MemberProductTimeMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMemberProductTimeItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MemberProductTimeItemServiceImpl implements IMemberProductTimeItemService {

    @Autowired
    private MemberProductTimeItemMapper mapper;
    @Autowired
    private MemberProductTimeMapper MPTmapper;

    public PageResult queryPage(QueryObject qo) {
        PageResult pr = new PageResult();
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return pr;
        }
        List<MemberProductTimeItem> rows = mapper.queryForList(qo);
        pr.setTotal(total);
        pr.setRows(rows);
        return pr;
    }

    public void save(MemberProductTimeItem entity) {
        MemberProductTime time = MPTmapper.selectById(entity.getTime().getId());
        if(time == null){   //如果没有次数表
            time = entity.getTime();
            entity.setBeginTime(time.getNumber());  //冲次前次数
            time.setNumber(entity.getNumber());
            time.setAddUpTime(entity.getNumber());
            MPTmapper.insert(time);
        }else{
            entity.setBeginTime(time.getNumber());  //冲次前次数
            time.setNumber(time.getNumber()+entity.getNumber());
            time.setAddUpTime(time.getAddUpTime()+entity.getNumber());
            MPTmapper.updateByPrimaryKey(time);
        }
        entity.setEndTime(time.getNumber());

        entity.setTimeDate(new Date());

        mapper.insert(entity);
    }
}
